<?php

namespace app\admin\controller;
use think\Db;
use think\Request;
use think\Controller;

class Con2 extends AdminController
{
    
    public function grouplist()
    {
        $list = Db::name('role')->field(true)->order('id', 'ASC')->select();
        
        return view('admin@con2/grouplist',[
            'list' => $list
        ]);
    }

    public function add()
    {
        return view('con2/add', [
            'title' => '添加新角色'
        ]);
    }


    public function doadd(Request $request)
    {
        $p = $request->post();


        $data = [
            'rolename' => $p['role']
        ];

        $result = Db::table('role')->data($data)->insert();

        if ($result > 0) {
            return $this->success('添加成功', url('admin/con2/grouplist'));
        } else {
            return $this->error('添加失败');
        }
    }


    public function shownode($id)
    {
        // 查看所有权限
        $nodelist = Db::table('node')->select();

        // 查看当前角色信息
        $user = Db::table('role')->where('id', $id)->find();


        // 获取当前角色的权限
        $ro_node = Db::table('grno')->where('role_id',$id)->select();


        $data = array();
        foreach ($ro_node as $v) {
            $data[] = $v['node_id'];
        }


        return view('con2/nodelist', [
           'nodes' => $nodelist,
           'user' => $user,
           'data' => $data
        ]);
    }



    public function savenode(Request $request)
    {
        $p = $request->post();

        $gid = $p['id'];


        if (empty($p)) {
            $this->error('请选择一个权限');
        }
            
        // 保证不重复 需要先删除
        Db::table('grno')->where('role_id', $p['id'])->delete();

        foreach ($p['node'] as $v) {
            $data['role_id'] = $gid;
            $data['node_id'] = $v;

            $res = Db::table('grno')->data($data)->insert();
        }

        if ($res > 0) {
            return $this->success('分配权限成功', url('admin/con2/grouplist'));
        } else {
            return $this->error('分配权限失败');
        }
    }

  

}
